<template>
  <div>
    <el-card style="width:98%;margin:30px auto;">
      <span style="font-weight:bold;font-size:17px">操作日志</span>

      <div style="display:flex;justify-content: space-between">
        <!--插入和批量删除-->
        <div style="margin: 10px -10px">
          <el-button type="danger" size="small" icon="el-icon-delete" @click="delBatch" title="批量删除" slot="reference"
                     style="margin-left: 10px"></el-button>
        </div>
        <div style="margin: 10px 5px">
          <el-input style="width: 200px" placeholder="请输入模块名" suffix-icon="el-icon-search"
                    v-model.trim="optModule"></el-input>
        <!--  <el-input style="width: 200px;margin-left: 5px" placeholder="请输入请求方法" suffix-icon="el-icon-search"
                    v-model.trim="optMethod"></el-input>-->
          <el-select clearable v-model="optMethod"  placeholder="请选择请求方法" style="margin-left: 10px">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>

          <el-button class="ml-5" type="primary" style="margin-left: 10px" @click="load">搜索</el-button>
          <el-button type="warning" @click="reset">重置</el-button>
        </div>


      </div>
      <!--模糊查询-->


      <!--表格渲染-->
      <el-table :data="tableData" :header-cell-class-name="'headerBg'"
                @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" ></el-table-column>
        <!--<el-table-column prop="id" label="ID" width="80"></el-table-column>-->
        <el-table-column
          prop="optModule"
          label="系统模块"
          align="center"
        >

        </el-table-column>

        <el-table-column prop="optType" label="操作类型"></el-table-column>
        <el-table-column prop="optDesc" label="操作描述" align="center"></el-table-column>
        <el-table-column prop="requestMethod" label="请求方式" align="center">

          <template slot-scope="scope" v-if="scope.row.requestMethod">
            <el-tag :type="tagType(scope.row.requestMethod)">
              {{ scope.row.requestMethod }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="操作人员"></el-table-column>
        <el-table-column prop="ipAddress" label="登录ip"  ></el-table-column>
        <el-table-column prop="ipSource" label="登录地址"  align="center"></el-table-column>
        <el-table-column prop="createTime" label="操作日期"    :formatter="dateFormat" align="center">

        </el-table-column>


        <el-table-column label="操作" width="120" align="center">

          <template slot-scope="scope">

            <el-button type="primary" @click="edit(scope.row)" icon="el-icon-edit" circle></el-button>

            <el-button @click="del(scope.row.id)" title="删除"
                       slot="reference" type="danger" icon="el-icon-delete" circle
                       style="margin-left: 10px"></el-button>

          </template>
        </el-table-column>
      </el-table>


      <!--分页-->
      <div style="padding: 10px 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>


    </el-card>

    <!--弹窗-->
    <el-dialog  :visible.sync="addDialogVisible" width="30%" >

      <div class="dialog-title-container" slot="title">
        <i class="el-icon-more" />详细信息
      </div>
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-form-item label="操作模块：">
          {{ form.optModule }}
        </el-form-item>
        <el-form-item label="请求地址：">
          {{ form.optUrl }}
        </el-form-item>
        <el-form-item label="请求方式：">
          <el-tag :type="tagType(form.requestMethod)">
            {{ form.requestMethod }}
          </el-tag>
        </el-form-item>
        <el-form-item label="操作方法：">
          {{ form.optMethod }}
        </el-form-item>
        <el-form-item label="请求参数：">
          {{ form.requestParam }}
        </el-form-item>
        <el-form-item label="返回数据：">
          {{ form.responseData }}
        </el-form-item>
        <el-form-item label="操作人员：">
          {{ form.nickname }}
        </el-form-item>
      </el-form>

    </el-dialog>
  </div>
</template>

<script>
  import {serverIp} from '../../../public/config';
  import qs from 'qs'
  export default {
    name: "index",
    data() {
      return {
        options: [{
          value: 'POST',
          label: 'POST'
        }, {
          value: 'DELETE',
          label: 'DELETE'
        },
          {
            value: 'PUT',
            label: 'PUT'
          },{
            value: 'GET',
            label: 'GET'
          }

        ],



        loading: true,
        optModule: '',
        optMethod: '',
        dialogVisible1: false,

        form: {},
        addDialogVisible: false,
        serverIp: serverIp,

        tableData: [],
        multipleSelection: [],
        pageNum: 1,
        pageSize: 10,
        total: 0,
        roles: [],

      }
    },

    computed: {
      tagType() {
        return function (type) {
          switch (type) {
            case "GET":
              return "";
            case "POST":
              return "success";
            case "PUT":
              return "warning";
            case "DELETE":
              return "danger";
          }
        };
      }
      },
    created() {
      this.load()
      this.request.get("/role").then(res => {
        this.roles = res.data
      })
    },
    methods: {
      //日期转换
      dateFormat(row, column, cellValue, index) {
        const daterc = row[column.property]
        if (daterc != null) {
          var date = new Date(daterc);
          var year = date.getFullYear();
          /* 在日期格式中，月份是从0开始，11结束，因此要加0
           * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
           * */
          var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
          var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
          var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
          var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
          var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
          // 拼接
          return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        }
      },




//编辑弹窗
      edit(row) {
        if (this.$store.state.user.role=='ROLE_ADMIN' || this.$store.state.user.role=='ROLE_ROOT') {
          this.form = JSON.parse(JSON.stringify(row))
          this.addDialogVisible = true

        }else{
          this.$notify.error({
            title: '失败',
            message: '您没有权限查看',
            duration: 4500
          });
        }

      },


      //初始化分页
      load() {
        this.request.get("/log/findPage", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            optModule: this.optModule,
            optMethod: this.optMethod,
          }
        }).then(res => {
          this.tableData = res.data.content
          this.total = res.data.totalElements

        })
      },


      //根据id进行删除
      del(id) {
       if (this.$store.state.user.role=='ROLE_ADMIN' || this.$store.state.user.role=='ROLE_ROOT') {
         this.$confirm('你确定要删除,是否继续?', '提示', {
           confirmButtonText: '确定',
           cancelButtonText: '取消',
           customClass: 'msgbox',
           type: 'warning'
         }).then(async () => {
           this.request.delete("/log/deleteById/" + id).then(res => {
             if (res.code === 200) {
               this.$message({message: '删除成功', type: "success"})
               this.load()
             } else {
               this.$message({message: '删除失败', type: "error"})
             }
           })
         }).catch(() => {
           this.$message({
             message: '已取消删除',
             type: 'success'
           })
         })
       }else {
         this.$notify.error({
           title: '失败',
           message: '权限不足',
           duration: 4500
         });
       }

       },

      //多选框
      handleSelectionChange(val) {
        this.multipleSelection = val
      },

      //批量删除
      delBatch() {
        this.$confirm('你确定要批量删除,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass: 'msgbox',
          type: 'warning'
        }).then(async () => {
          let ids = this.multipleSelection.map(v => v.id)
          // qs.stringify({ids:ids})
          this.request.post("/log/del/batch", ids).then(res => {
            if (ids.length === 0) {
              this.$message({
                type: 'warning',
                message: '请选择数据!'
              });
              return
            }

            if (res.code === 200) {
              this.$message({message: '批量删除成功', type: "success"})
              this.load()
            } else {
              this.$message({message: '批量删除失败', type: "error"})
            }
          })
        }).catch(() => {
          this.$message({
            message: '已取消删除',
            type: 'success'
          })
        })
      },

      //重置
      reset() {
        this.optMethod=""
        this.optModule = ""
        this.optType = ""
        this.load()
      },

      //当前页面的个数
      handleSizeChange(pageSize) {
        this.pageSize = pageSize
        this.load()
      },

      //当前页面从哪里开始
      handleCurrentChange(pageNum) {
        this.pageNum = pageNum
        this.load()
      },


    }
  }
</script>


<style >

@media (max-width: 720px) {
  .msgbox{
    width: 327px !important;
  }
}

</style>
